/**
 * 用户管理模块
 */
class UserManager {
    constructor() {
        this.currentUser = null;
        this.users = [];
        this.roles = {};
        this.loadUsers();
    }

    /**
     * 从服务器加载用户数据
     */
    async loadUsers() {
        try {
            const response = await fetch('/api/users');
            if (response.ok) {
                const data = await response.json();
                this.users = data.users || [];
                this.roles = data.roles || {};
            }
        } catch (error) {
            console.error('加载用户数据失败:', error);
        }
    }

    /**
     * 用户登录
     */
    async login(username, password) {
        try {
            const response = await fetch('/api/login', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ username, password })
            });

            if (response.ok) {
                const result = await response.json();
                this.currentUser = result.user;
                localStorage.setItem('currentUser', JSON.stringify(result.user));
                return result;
            } else {
                const error = await response.json();
                return { success: false, message: error.message };
            }
        } catch (error) {
            console.error('登录失败:', error);
            return { success: false, message: '网络错误，请重试' };
        }
    }

    /**
     * 用户登出
     */
    logout() {
        this.currentUser = null;
        localStorage.removeItem('currentUser');
        localStorage.removeItem('isLoggedIn');
        localStorage.removeItem('username');
    }

    /**
     * 获取当前用户
     */
    getCurrentUser() {
        if (!this.currentUser) {
            const stored = localStorage.getItem('currentUser');
            if (stored) {
                this.currentUser = JSON.parse(stored);
            }
        }
        return this.currentUser;
    }

    /**
     * 检查用户权限
     */
    hasPermission(permission) {
        const user = this.getCurrentUser();
        if (!user || !user.role) return false;
        
        const role = this.roles[user.role];
        return role && role.permissions && role.permissions.includes(permission);
    }

    /**
     * 检查是否为超级管理员
     */
    isSuperAdmin() {
        const user = this.getCurrentUser();
        if (!user) return false;
        
        // 直接检查角色，或者检查权限
        return user.role === 'super_admin' || this.hasPermission('user_management');
    }

    /**
     * 获取所有用户
     */
    async getAllUsers() {
        try {
            const response = await fetch('/api/users');
            if (response.ok) {
                const data = await response.json();
                return data.users || [];
            }
        } catch (error) {
            console.error('获取用户列表失败:', error);
        }
        return [];
    }

    /**
     * 添加用户
     */
    async addUser(userData) {
        try {
            const response = await fetch('/api/users', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(userData)
            });

            if (response.ok) {
                const newUser = await response.json();
                this.users.push(newUser);
                return { success: true, user: newUser };
            } else {
                const error = await response.json();
                return { success: false, message: error.message };
            }
        } catch (error) {
            console.error('添加用户失败:', error);
            return { success: false, message: '网络错误，请重试' };
        }
    }

    /**
     * 删除用户
     */
    async deleteUser(userId) {
        try {
            const response = await fetch(`/api/users/${userId}`, {
                method: 'DELETE'
            });

            if (response.ok) {
                this.users = this.users.filter(user => user.id !== userId);
                return { success: true };
            } else {
                const error = await response.json();
                return { success: false, message: error.message };
            }
        } catch (error) {
            console.error('删除用户失败:', error);
            return { success: false, message: '网络错误，请重试' };
        }
    }

    /**
     * 更新用户
     */
    async updateUser(userId, userData) {
        try {
            const response = await fetch(`/api/users/${userId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(userData)
            });

            if (response.ok) {
                const updatedUser = await response.json();
                const index = this.users.findIndex(user => user.id === userId);
                if (index !== -1) {
                    this.users[index] = updatedUser;
                }
                return { success: true, user: updatedUser };
            } else {
                const error = await response.json();
                return { success: false, message: error.message };
            }
        } catch (error) {
            console.error('更新用户失败:', error);
            return { success: false, message: '网络错误，请重试' };
        }
    }

    /**
     * 获取角色列表
     */
    getRoles() {
        return this.roles;
    }
}

// 创建全局实例
window.userManager = new UserManager();
